<template>
  <div class="auth-container">
    <div class="auth-card">
      <div class="auth-header">
        <h2>登录</h2>
        <p>欢迎回到云顶AI自习室</p>
      </div>

      <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="loginRules"
        class="auth-form"
        @submit.prevent="handleLogin"
      >
        <!-- <el-tabs v-model="loginType" class="login-tabs"> -->
          <!-- <el-tab-pane label="账号密码" name="password"> -->
            <el-form-item prop="username">
              <el-input
                v-model="loginForm.username"
                placeholder="请输入用户名/邮箱/手机号"
                size="large"
                :prefix-icon="User"
              />
            </el-form-item>

            <el-form-item prop="password">
              <el-input
                v-model="loginForm.password"
                type="password"
                placeholder="请输入密码"
                size="large"
                :prefix-icon="Lock"
                show-password
              />
            </el-form-item>
            <el-form-item prop="verifyCode">
            <div class="verify-code-row">
              <el-input v-model="loginForm.verifyCode" placeholder="请输入验证码" style="flex:1;height: 40px;" />
              <el-image
                style="width: 100px; height: 40px; border-radius: 8px; margin-left: 12px;cursor: pointer;"
                :src="imgObj.captchUrl"
                @click="getCaptch"
              ></el-image>
            </div>
          </el-form-item>
          <!-- </el-tab-pane> -->

          <!-- <el-tab-pane label="短信验证码" name="sms"> -->
            <!-- <el-form-item prop="phone">
              <el-input
                v-model="loginForm.phone"
                placeholder="请输入手机号"
                size="large"
                :prefix-icon="Phone"
              />
            </el-form-item>

            <el-form-item prop="smsCode">
              <div class="sms-input">
                <el-input
                  v-model="loginForm.smsCode"
                  placeholder="请输入验证码"
                  size="large"
                  :prefix-icon="Message"
                />
                <el-button
                  type="primary"
                  size="large"
                  :disabled="smsCountdown > 0"
                  @click="sendSmsCode"
                >
                  {{ smsCountdown > 0 ? `${smsCountdown}s` : "发送验证码" }}
                </el-button>
              </div>
            </el-form-item> -->
          <!-- </el-tab-pane> -->
        <!-- </el-tabs> -->

        <div class="form-options">
          <el-checkbox v-model="rememberMe">记住我</el-checkbox>
          <!-- <el-link type="primary">忘记密码？</el-link> -->
        </div>

        <el-form-item>
          <el-button
            type="primary"
            size="large"
            class="auth-button"
            :loading="loading"
            @click="handleLogin"
          >
            登录
          </el-button>
        </el-form-item>

        <!-- <div class="oauth-section">
          <div class="divider">
            <span>或使用以下方式登录</span>
          </div>
          <div class="oauth-buttons">
            <el-button circle size="large" @click="handleOAuthLogin('wechat')">
              <el-icon><ChatDotRound /></el-icon>
            </el-button>
            <el-button circle size="large" @click="handleOAuthLogin('qq')">
              <el-icon><User /></el-icon>
            </el-button>
            <el-button circle size="large" @click="handleOAuthLogin('github')">
              <el-icon><Link /></el-icon>
            </el-button>
          </div>
        </div> -->
      </el-form>

      <div class="auth-footer">
        <span class="footer-text">还没有账号？</span>
        <el-link type="primary" @click="goToRegister" class="footer-link">立即注册</el-link>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive,onMounted,onUnmounted } from "vue";
import { useRouter,useRoute  } from "vue-router";
import { useUserStore } from "@/stores";
import { ElMessage } from "element-plus";
import {
  User,
  Lock,
  Phone,
  Message,
  ChatDotRound,
  Link,
} from "@element-plus/icons-vue";
import type { FormInstance, FormRules } from "element-plus";
import { login } from "@/api/user";
import { getCode } from "@/api/user";

const router = useRouter();
const route = useRoute();
const userStore = useUserStore();

const loginFormRef = ref<FormInstance>();
const loginType = ref("password");
const loading = ref(false);
const rememberMe = ref(false);
const smsCountdown = ref(0);

const loginForm = reactive({
  username: "",
  password: "",
  phone: "",
  smsCode: "",
  verifyCode: "",
  codeId:"",
});

const loginRules: FormRules = {
  username: [
    { required: true, message: "请输入用户名/邮箱/手机号", trigger: "blur" },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, message: "密码长度不能少于6位", trigger: "blur" },
  ],
  phone: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号",
      trigger: "blur",
    },
  ],
  smsCode: [
    { required: true, message: "请输入验证码", trigger: "blur" },
    { len: 6, message: "验证码为6位数字", trigger: "blur" },
  ],
};
// const handleLogin=async()=>{

//   if (!loginForm.username || !loginForm.password) {
//     ElMessage.error("请输入用户名和密码");
//     return;
//   }
 
//   const res = await login({
//     ...loginForm
//   })
//   console.log("登录请求结果：", res);
  
//   if (res.code == 200) {
//     userStore.login(res.data.user);
//     ElMessage.success("登录成功");
//     router.push("/home");
//    console.log("登录结果：", res);

//   } else {
//     ElMessage.error( "登录失败，请检查账号信息");
// }
// }
const imgObj = reactive({
  captchUrl: ""
})

   //获取验证码
    const getCaptch = async() => {
      const res = await getCode({
        ...loginForm
      });
      console.log("获取验证码结果：", res);  
  //发送请求获取验证码图片
            // console.log(res);
            if(res.code == 200){ //表示获取验证码成功
                //把验证码图片地址赋值给imgObj
                imgObj.captchUrl = res.data.base64Code;
                loginForm.codeId =res.data.codeId;
            }else{ //表示获取验证码失败  
                ElMessage.error("获取验证码失败，请稍后再试");
            }       
    }
    //页面加载时获取验证码
    onMounted(() => {
        getCaptch();
    })

// const handleLogin = async () => {
//   if (!loginFormRef.value) return;

//   try {
//     debugger;
//     await loginFormRef.value.validate();
//     loading.value = true;

//     const mockUser = {
//       id: "1",
//       username: loginForm.username || loginForm.phone,
//       nickname: "用户昵称",
//       email: "user@example.com",
//       phone: loginForm.phone || "13800138000",
//       avatar: "",
//       gender: "男",
//       education: "本科",
//       studySubjects: ["计算机科学"],
//       studyTime: 0,
//       isOnline: true,
//     };

//     userStore.login(mockUser);
//     ElMessage.success("登录成功");
//     router.push("/");
//   } catch (error) {
//     ElMessage.error("登录失败，请检查账号信息");
//   } finally {
//     loading.value = false;
//   }
// };

const sendSmsCode = () => {
  if (!loginForm.phone) {
    ElMessage.warning("请先输入手机号");
    return;
  }

  smsCountdown.value = 60;
  const timer = setInterval(() => {
    smsCountdown.value--;
    if (smsCountdown.value <= 0) {
      clearInterval(timer);
    }
  }, 1000);

  ElMessage.success("验证码已发送");
};

const handleOAuthLogin = (provider: string) => {
  ElMessage.info(`${provider} 登录功能开发中`);
};

const goToRegister = () => {
  router.push("/auth/register");
};

// 处理其他设备登录提示
if (route.query.message) {
  ElMessage.warning(route.query.message);
  router.replace({ query: null });
}

const handleLogin = async () => {
  try {
    const res = await userStore.login({
      username: loginForm.username,
      password: loginForm.password,
      verifyCode: loginForm.verifyCode,
      codeId: loginForm.codeId
    });
    
    if (res.code === 200) {
      ElMessage.success("登录成功");
      router.push("/home");
    }
  } catch (error) {
    getCaptch(); // 刷新验证码
  }
};

// 组件卸载时移除监听
onUnmounted(() => {
  window.removeEventListener("storage", userStore.handleStorageEvent);
});
</script>

<style scoped>
.auth-container {
  width: 100%;
  max-width: 400px;
}

.auth-card {
  background: white;
  border-radius: 16px;
  padding: 40px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
}

.auth-header {
  text-align: center;
  margin-bottom: 30px;
}

.auth-header h2 {
  margin: 0 0 8px 0;
  color: #2c3e50;
  font-size: 2rem;
  font-weight: bold;
}

.auth-header p {
  margin: 0;
  color: #7f8c8d;
}

.auth-form {
  margin-bottom: 20px;
}

.footer-text,
.footer-link {
  font-size: 14px;
  line-height: 20px; /* 统一字体高度 */
}

.footer-text {
  color: #7f8c8d;
}

.footer-link {
  height: 20px; /* 确保链接高度一致 */
}

.footer-link :deep(.el-link__inner) {
  font-size: 14px;
  line-height: 20px;
  height: 20px;
}

.login-tabs {
  margin-bottom: 20px;
}

.sms-input {
  display: flex;
  gap: 12px;
}

.sms-input .el-input {
  flex: 1;
}

.form-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.auth-button {
  width: 100%;
}

.oauth-section {
  margin-top: 30px;
}

.divider {
  text-align: center;
  position: relative;
  margin-bottom: 20px;
}

.divider::before {
  content: "";
  position: absolute;
  top: 50%;
  left: 0;
  right: 0;
  height: 1px;
  background: #e4e7ed;
}

.divider span {
  background: white;
  padding: 0 16px;
  color: #7f8c8d;
  font-size: 14px;
}

.oauth-buttons {
  display: flex;
  justify-content: center;
  gap: 16px;
}

.auth-footer {
  display: flex;
  align-items: center;
  justify-content: flex-end; /* 靠右对齐 */
  gap: 8px; /* 两个元素之间的间距 */
  margin-top: 20px;
}

.verify-code-row {
  display: flex;
  align-items: center;
  gap: 12px;
}

.verify-code-row :deep(.el-input__wrapper) {
  height: 40px;
  align-items: center;
}

.verify-code-row :deep(.el-input__inner) {
  height: 40px;
  line-height: 40px;
}
</style>
